package com.runvp.rest.biz;

import com.runvp.common.annotation.Log;
import com.runvp.common.core.controller.BaseController;
import com.runvp.common.core.domain.AjaxResult;
import com.runvp.common.core.domain.entity.SysUser;
import com.runvp.common.core.page.TableDataInfo;
import com.runvp.common.enums.BusinessType;
import com.runvp.common.enums.EnableStatus;
import com.runvp.common.enums.UserType;
import com.runvp.common.utils.ShiroUtils;
import com.runvp.service.biz.domain.BizCustomer;
import com.runvp.service.biz.service.IBizCustomerService;
import com.runvp.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 云卡
 *
 * @author update for xkk
 */
@Slf4j
@Controller
@RequestMapping("/biz/partners/distribution/cloud/card")
public class DistributionCloduCardController extends BaseController {
    private String prefix = "biz/partners";

    @Autowired
    private ISysUserService userService;
    @Autowired
    private IBizCustomerService bizCustomerService;


    /**
     * 分配设备
     */
    @RequiresPermissions("system:user:edit")
    @GetMapping("/{userId}")
    public String distributionDevice(@PathVariable("userId") Long userId, ModelMap mmap) {
        SysUser user = userService.selectUserById(userId);
        mmap.put("user", user);
        return prefix + "/cloudCard";
    }

    /**
     * 查询已分配列表
     */
    @RequiresPermissions("biz:device:list")
    @PostMapping("/allocatedList")
    @ResponseBody
    public TableDataInfo allocatedList(BizCustomer query) {
        startPage();
        query.setType(UserType.CLOUD_CARD.getCode());
        query.setStatus(EnableStatus.ENABLE.getCode());
        query.setPid(query.getTenantId());
        List<BizCustomer> datas = bizCustomerService.selectBizCustomerList(query);
        return getDataTable(datas);
    }

    /**
     * 选择设备
     */
    @GetMapping("/select/{tenantId}")
    public String selectUser(@PathVariable("tenantId") Long tenantId, ModelMap mmap) {
        SysUser user = userService.selectUserById(tenantId);
        mmap.put("user", user);
        return prefix + "/selectCloudCard";
    }

    /**
     * 查询未分配设备列表
     */
    @RequiresPermissions("biz:device:list")
    @PostMapping("/unallocatedList")
    @ResponseBody
    public TableDataInfo unallocatedList(BizCustomer query) {
        startPage();
        query.setType(UserType.CLOUD_CARD.getCode());
        query.setStatus(EnableStatus.ENABLE.getCode());
        query.getParams().put("dynamicCondition", " AND pid = 0 AND pid != " + query.getTenantId());
        query.setPid(null);
        List<BizCustomer> datas = bizCustomerService.selectBizCustomerList(query);
        return getDataTable(datas);
    }

    /**
     * 批量绑定设备
     */
    @RequiresPermissions("biz:device:edit")
    @Log(title = "批量绑定设备", businessType = BusinessType.GRANT)
    @PostMapping("/selectAll")
    @ResponseBody
    public AjaxResult selectDistributionDeviceAll(Long tenantId, Long[] cloudCardIds) {
        log.info("分配设备tenantId:{},cloudCardIds:{}", tenantId, cloudCardIds);
        //获取该用户的所有设备
        BizCustomer data;
        for (Long id : cloudCardIds) {
            data = bizCustomerService.selectBizCustomerById(id);
            if (null == data) {
                log.error("云卡id为【{}】的卡不存在,跳过绑定", id);
                continue;
            }
            data.setPid(tenantId);
            data.setUpdateBy(ShiroUtils.getLoginName());
            bizCustomerService.updateBizCustomer(data);
        }
        return success();
    }

    /**
     * 取消绑定
     */
    @RequiresPermissions("biz:device:edit")
    @Log(title = "取消绑定", businessType = BusinessType.GRANT)
    @PostMapping("/cancel")
    @ResponseBody
    public AjaxResult cancelDistributionDevice(Long cloudCardId) {
        cancel(cloudCardId);
        return success();
    }

    /**
     * 批量取消绑定
     */
    @RequiresPermissions("biz:device:edit")
    @Log(title = "批量取消绑定", businessType = BusinessType.GRANT)
    @PostMapping("/cancelAll")
    @ResponseBody
    public AjaxResult cancelDistributionDeviceAll(Long[] cloudCardIds) {
        for (Long id : cloudCardIds) {
            cancel(id);
        }
        return success();
    }

    /**
     * 取消绑定
     *
     * @param cloudCardId
     */
    private void cancel(Long cloudCardId) {
        BizCustomer data = bizCustomerService.selectBizCustomerById(cloudCardId);
        if (null == data) {
            log.error("云卡id为【{}】的卡不存在,跳过绑定", cloudCardId);
            return;
        }
        data.setPid(0L);
        data.setUpdateBy(ShiroUtils.getLoginName());
        bizCustomerService.updateBizCustomer(data);
    }

}